package com.heima.behavior.service.impl;

import com.heima.behavior.dto.UnLikesBehaviorDto;
import com.heima.behavior.entity.ApUnlikesBehavior;
import com.heima.behavior.service.IUnlikeService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.entity.User;
import com.heima.common.util.AppThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UnlikerService implements IUnlikeService {
    @Autowired
    private MongoTemplate template;
    @Override
    public ResponseResult unlke(UnLikesBehaviorDto dto) {
//        创建不喜欢对象
        ApUnlikesBehavior apUnlikesBehavior = new ApUnlikesBehavior();
        User user = AppThreadLocal.get();
        if (user != null){
            apUnlikesBehavior.setUserId(user.getUserId());
        }else {
            apUnlikesBehavior.setEquipmentId(dto.getEquipmentId());
        }
        apUnlikesBehavior.setArticleId(dto.getArticleId());
        apUnlikesBehavior.setType(0);
        apUnlikesBehavior.setCreatedTime(new Date());

//        查询是否存在
        Query query = new Query();
        query.addCriteria(Criteria.where("authorId").is(dto.getArticleId()));
        if (user != null){
            query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        }else {
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }
        ApUnlikesBehavior one = template.findOne(query, ApUnlikesBehavior.class);
//        判断是否为空
        if (one == null){
            template.save(apUnlikesBehavior);
        }else {
            if (dto.getType() != one.getType()){
                one.setType(dto.getType());
                template.save(one);
            }
        }


        return ResponseResult.okResult();
    }
}
